/*
 * @Author: zhangyang
 * @Date: 2021-07-03 15:05:07
 * @LastEditTime: 2022-08-02 17:33:27
 * @Description: 自定义工具函数
 */
export const sleep = async (n: number) => {
  return new Promise((resolve) => setTimeout(resolve, n * 1000));
};

import { useClipboard } from '@vueuse/core';
export const copy2Clipboard = async (str: string) => {
  const { copy, copied, isSupported } = useClipboard();
  if (isSupported) {
    await copy(str);
    if (copied.value) {
      window.$message.success('已复制到剪切板！');
    } else {
      window.$message.error('复制失败！');
    }
  } else if (document.execCommand) {
    const el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    window.$message.success('已复制到剪切板！');
  } else {
    window.$message.error('浏览器不支持！');
  }
};
/**
 * 状态切换带函数执行，初始状态为假
 * @param f1 首次执行的函数
 * @param f2 状态变换之后执行的函数
 * @returns [v: Ref<boolean>, toggleFn: () => void]
 */
import type { Ref } from 'vue';
import { isObject, isString } from './isType';
export const useToggle = (f1: Function, f2: Function): [Ref<boolean>, () => void] => {
  const v = ref(false);
  return [v, () => {
      v.value ? f2() : f1();
      v.value = !v.value;
    }
  ];
};
const parseDo = (str: string, sep = '%') => {
  const arr: string[] = [];
  str.split(sep).map((item) => {
    if (item) {
      const s = item.replace('u', '0x');
      if (s.length > 6) {
        arr.push(String.fromCharCode(+s.substr(0, 6)), decodeURIComponent(s.slice(6)));
      } else if (s.length === 6) {
        arr.push(String.fromCharCode(+s));
      } else {
        arr.push(decodeURIComponent(s));
      }
    }
  });
  return arr.join('');
};
/**
 * 解析转义之后的字符串
 * @param str
 */
export const encodedStrParse = (str: string) => {
  if (str.includes('%u')) {
    return parseDo(str, '%');
  } else if (str.includes('\\u')) {
    return parseDo(str, '\\');
  } else {
    return decodeURIComponent(str);
  }
};

/**
 * 安全解析 JSON 字符串
 * @param {string} str
 */
export const safeJsonParse = <T extends any = any>(str: string, exp: any = {}): T => {
  if (isString(str)) {
    try {
      const obj = JSON.parse(str);
      if (isObject(obj) || isArray(obj)) {
        return obj;
      } else {
        return exp;
      }
    } catch (error) {
      return exp;
    }
  }
  return exp;
};